package com.chen.palmar.wxapi;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.Toast;

import com.chen.palmar.common.constant.AppConstant;
import com.primb.androidlibs.net.entity.MessageEvent;
import com.tencent.mm.opensdk.modelbase.BaseReq;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.greenrobot.eventbus.EventBus;

import dmax.dialog.SpotsDialog;
import rx.subscriptions.CompositeSubscription;

import static com.chen.palmar.project.set.AccountManagerActivity.EVENT_ACCOUNT_CODE;

/**
 * Created by chen on 2018/1/21.
 */

public class WXPayEntryActivity extends Activity implements IWXAPIEventHandler {
    private IWXAPI api;
    public CompositeSubscription subscription = new CompositeSubscription();
    public SpotsDialog spotsDialog;
    public static final int EVENT_WX_PAY_CODE = 2;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        api = WXAPIFactory.createWXAPI(this, AppConstant.APP_WX_ID);

        api.handleIntent(getIntent(), this);

    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);

        api.handleIntent(intent, this);
    }


    @Override
    public void onReq(BaseReq req) {
    }

    @Override
    public void onResp(BaseResp resp) {
        if (resp.errCode == 0) {
            EventBus.getDefault().post(new MessageEvent(EVENT_WX_PAY_CODE));
        } else {
            Toast.makeText(this, "微信支付失败", Toast.LENGTH_SHORT).show();
        }
        this.finish();
    }

    public SpotsDialog showLoading(String text) {
        if (null == spotsDialog) {
            spotsDialog = new SpotsDialog(this, text);
        }
        spotsDialog.show();
        return spotsDialog;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (null != subscription) {
            subscription.clear();
            subscription.unsubscribe();
        }
    }
}
